<template>
    <el-drawer title="修改库存" :size="1000" :visible.sync="visible" append-to-body direction="rtl" :before-close="close">
        <section class="stock-main" v-loading="loadingPage">
            <div class="title">
                <div class="line"></div>
                <h1>{{ goodsSingleForm.spec_type == 10 ? '单规格' : '多规格' }}</h1>
            </div>
            <el-form size="small" label-width="100px" class="form-con" :model="goodsSingleForm">
                <el-form-item label="商品名称" prop="goods_name">
                    <el-input placeholder="请输入商品名称" class="form-input" v-model="goodsSingleForm.goods_name"
                        readonly></el-input>
                </el-form-item>
                <div class="single-wrap" v-if="goodsSingleForm.spec_type == 10">
                    <el-form-item label="平台价" prop="goods_price">
                        <el-input v-model="goodsSingleForm.goods_price" class="form-input" placeholder="请输入平台价"
                            readonly></el-input>
                    </el-form-item>
                    <el-form-item label="销售价" prop="market_price">
                        <el-input v-model="goodsSingleForm.market_price" class="form-input" placeholder="请输入销售价"
                            readonly></el-input>
                    </el-form-item>
                    <el-form-item label="库存" prop="stock_num">
                        <el-input v-model="goodsSingleForm.stock_num" class="form-input" placeholder="请输入当前商品库存"
                            type="number"></el-input>
                    </el-form-item>
                    <el-form-item label="单位" prop="market_price">
                        <el-input :value="goodsSingleForm.goods_unit ? goodsSingleForm.goods_unit : '暂无'"
                            class="form-input" placeholder="请输入单位" readonly></el-input>
                    </el-form-item>
                    <el-form-item label="最低起卖数量" prop="minimum">
                        <el-input v-model="goodsSingleForm.minimum" class="form-input" placeholder="请输入最低起卖数量"
                            readonly></el-input>
                    </el-form-item>
                    <el-form-item label="商品编码">
                        <el-input :value="goodsSingleForm.goods_no ? goodsSingleForm.goods_no : '暂无'" class="form-input"
                            readonly></el-input>
                    </el-form-item>
                </div>
                <div class="multiple-wrap" v-else>
                    <el-form-item label="SKU列表">
                        <el-table border size="small" header-cell-class-name="header-cell" :data="skuData.skuList"
                            :span-method="spanMethod">
                            <el-table-column :prop="item.prop" :label="item.spec_name" v-for="(
                                            item, index
                                        ) in skuData.specList" :key="index"></el-table-column>
                            <el-table-column prop="image" label="预览图" width="105px">
                                <template slot-scope="scope">
                                    <div class="upload-img-wrap">
                                        <div class="upload-img-item">
                                            <el-image :src="scope.row.image" fit="contain" class="upload-img">
                                                <div slot="error" class="image-slot">
                                                    <p>暂无图片</p>
                                                </div>
                                            </el-image>
                                        </div>
                                    </div>
                                </template>
                            </el-table-column>
                            <el-table-column prop="goods_price" label="平台价">
                            </el-table-column>
                            <el-table-column prop="market_price" label="销售价">
                            </el-table-column>
                            <el-table-column prop="stock_num" label="库存数量" width="140px">
                                <template slot-scope="scope">
                                    <el-input v-model="scope.row.stock_num" @change="setSpecStock(scope.$index, $event)"
                                        type="number"></el-input>
                                </template>
                            </el-table-column>
                            <el-table-column prop="goods_unit" label="单位">
                                <template slot-scope="scope">
                                    {{ scope.row.goods_unit ? scope.row.goods_unit : '暂无' }}
                                </template>
                            </el-table-column>
                            <el-table-column label="最低起卖数量" prop="minimum">
                                <!-- <template slot-scope="scope">
                                    <el-input v-model="scope.row.minimum" @change="setSpecMinimum(scope.$index, $event)"
                                              :readonly="applyStatus == 10 || applyStatus == 30 ? false:true" type="number"></el-input>
                                </template> -->
                            </el-table-column>
                            <el-table-column prop="goods_sku_no" label="SKU编码">
                                <template slot-scope="scope">
                                    {{ scope.row.goods_sku_no ? scope.row.goods_sku_no : '暂无' }}
                                </template>
                            </el-table-column>
                        </el-table>
                    </el-form-item>
                </div>
                <el-form-item>
                    <el-button type="primary" :disabled="isDisabled" :loading="isLoading" @click="submitStock">提
                        交</el-button>
                </el-form-item>
            </el-form>
        </section>

    </el-drawer>
</template>
<script>
import { getGoodsDetail, goodsStockUpdate } from '../../../api/goods';
import debounce from "@/utils/debounce.js";
export default {
    name: 'editStock',
    data() {
        return {
            visible: false,
            goodsId: '',
            goodsSingleForm: {
                goods_name: "",
                spec_type: 10, // 10 单规格 20 多规格

                //单规格
                goods_price: "0",
                market_price: "0",
                stock_num: "9999",
                goods_unit: "",
                minimum: "1",
                goods_no: '',
            },
            //多规格数据操作
            skuData: {
                specList: [],
                skuList: [],
            },
            defaultSkuItemData: [{
                image: "",
                goods_price: '',
                market_price: '',
                stock_num: '9999',
                goods_unit: "",
                minimum: 1,
                goods_sku_no: "",
            }],
            loadingPage: false,
            goodsStockList: [],
            isDisabled: false,
            isLoading: false,
        }
    },
    created() {

    },
    methods: {
        getGoodsDetail() {
            getGoodsDetail({
                goods_id: this.goodsId,
                goods_type: 20,
            }).then((res) => {
                this.loadingPage = false;
                if (res.code == 0) {
                    this.setGoodsData(res.data);
                }
            });
        },
        setGoodsData(data) {
            this.goodsSingleForm.goods_name = data.goods_name;
            this.goodsSingleForm.spec_type = data.spec_type;
            if (data.spec_type == 10) {
                this.goodsSingleForm.goods_price = data.goods_price;
                this.goodsSingleForm.market_price = data.market_price;
                this.goodsSingleForm.stock_num = data.stock_total;
                this.goodsSingleForm.goods_unit = data.goods_unit;
                this.goodsSingleForm.minimum = data.minimum;
                this.goodsSingleForm.goods_no = data.goods_no;
                this.goodsSingleForm.goods_sku_id = data.skuList[0].id;
            } else {
                this.setMultipleData(data.specList, data.skuList)
            }
            this.relationGoods = data.rel_good_arr;
        },
        //编辑商品详情的时候 整理规格数据
        setMultipleData(specList, skuList) {
            let newSkuList = [];
            specList.forEach((v, i) => {
                v.prop = `spec_value_${i}`
            })
            let cartesianList = this.cartesianProductOfSkus(specList),
                newSkuArr = [];
            skuList.forEach((v, i) => {
                const newSkuObj = {
                    ...v,
                    ...cartesianList[i]
                }
                newSkuArr.push(newSkuObj)
            })
            this.skuData.specList = specList;
            this.skuData.skuList = newSkuArr;
            this.isInputAtrr = true;
        },
        cartesianProductOfSkus(skus) {
            function descriptorToObject(descriptor) {
                let attrObj = {};
                let skuKeys = [];
                let skuSelectKeyArr = [];
                let skuKey = "";
                descriptor.forEach((attrValueObj, index) => {
                    var skuKeyObj = {
                        groupKey: attrValueObj.groupKey,
                        valueKey: attrValueObj.key,
                    };
                    var skuSelectKey = attrValueObj.key;
                    skuKeys.push(skuKeyObj);
                    skuSelectKeyArr.push(skuSelectKey);
                    skuKey = skuSelectKeyArr.join("_");
                    attrObj[skus[index].prop] = attrValueObj.spec_value;
                });
                attrObj.skuKeys = skuKeys
                attrObj.skuKey = skuKey
                return attrObj
            }
            function cartesianProduct(a) {
                if (a.length === 0) return [[]];

                let result = [];
                let rest = cartesianProduct(a.slice(1));
                for (let i = 0; i < a[0].length; i++) {
                    for (let j = 0; j < rest.length; j++) {
                        result.push([a[0][i]].concat(rest[j]));
                    }
                }
                return result;
            }
            let descriptors = skus.map((sku) => sku.valueList);
            let combos = cartesianProduct(descriptors);
            return combos.map(descriptorToObject);
        },
        spanMethod({ row, column, rowIndex, columnIndex }) {
            const fields = ["spec_value_0"];
            // 当前行的数据
            const cellValue = row[column.property];
            // 判断只合并定义字段的列数据
            if (cellValue && fields.includes(column.property)) {
                const prevRow = this.skuData.skuList[rowIndex - 1]; //上一行数据
                let nextRow = this.skuData.skuList[rowIndex + 1]; //下一行数据
                // 当上一行的数据等于当前行数据时，当前行单元格隐藏
                if (prevRow && prevRow[column.property] === cellValue) {
                    return {
                        rowspan: 0,
                        colspan: 0,
                    };
                } else {
                    // 反之，则循环判断若下一行数据等于当前行数据，则当前行开始进行合并单元格
                    let countRowspan = 1; //用于合并计数多少单元格
                    while (nextRow && nextRow[column.property] === cellValue) {
                        nextRow =
                            this.skuData.skuList[++countRowspan + rowIndex];
                    }
                    if (countRowspan > 1) {
                        return {
                            rowspan: countRowspan,
                            colspan: 1,
                        };
                    }
                }
            }
        },
        setSpecStock(index, e) {
            debounce(() => {
                this.skuData.skuList[index].stock_num = e;
            });
        },
        setStockData() {
            switch (Number(this.goodsSingleForm.spec_type)) {
                case 10:
                    this.goodsStockList.push({
                        stock_num: this.goodsSingleForm.stock_num,
                        goods_sku_id: this.goodsSingleForm.goods_sku_id
                    })
                    break;
                case 20:
                    var goodsStockList = [];
                    goodsStockList = this.skuData.skuList.map(v => {
                        return {
                            stock_num: v.stock_num,
                            goods_sku_id: v.id
                        }
                    })
                    this.goodsStockList = goodsStockList;
                    break;
            }
        },
        submitStock() {
            this.setStockData();
            this.isDisabled = true;
            this.isLoading = true;
            goodsStockUpdate({
                goods_id: this.goodsId,
                goodsStockList: JSON.stringify(this.goodsStockList)
            }).then(res => {
                if (res.code == 0) {
                    this.$message.success(res.msg);
                    this.isDisabled = false;
                    this.isLoading = false;
                    this.close();
                    this.$emit('reload')
                } else {
                    this.isDisabled = false;
                    this.isLoading = false;
                }
            })
        },
        clearData() {
            this.goodsSingleForm = {
                goods_name: "",
                spec_type: 10, // 10 单规格 20 多规格

                //单规格
                goods_price: "0",
                market_price: "0",
                stock_num: "0",
                minimum: "1",
                goods_no: '',
            };
            this.skuData = {
                specList: [],
                skuList: [],
            }
            this.goodsStockList = []
        },
        show() {
            this.visible = true;
        },
        close() {
            this.visible = false;
            this.clearData()
        },
    }
}
</script>
<style scoped>
/deep/ .el-drawer__header {
    font-size: 14px;
    font-weight: bold;
    border-bottom: 1px solid #eee;
    padding: 12px;
    margin-bottom: 0;
}

.stock-main {
    padding: 15px;
}

.title {
    display: flex;
    align-items: center;
    margin-bottom: 15px;
}

.line {
    width: 3px;
    height: 14px;
    background-color: var(--main-color);
}

.title h1 {
    font-size: 14px;
    color: #515a6e;
    margin-left: 8px;
}
</style>